#!/usr/bin/php
<?php

date_default_timezone_set('America/New_York');

function checkServer($server)
{
	$version    = date("Y.m.d");
	$workingDir = __DIR__;
	$packager   = $workingDir . "/packageIPPPrinter.py";

	echo "=========================================================\n";
	echo "Creating printers from '${server}'\n";
	echo "=========================================================\n";

	$pList=`iprntcmd -L "${server}" | sed -n "3,100000p" | sed "s/^[ ]*//"`;

	$printers = explode("\n", trim($pList));
	$totalPrinters = count($printers);
	for($i = 0; $i < $totalPrinters; $i++)
	{
		$printer = $printers[$i];
		$isSecure = strpos($printer, "_secure") !== FALSE
			? TRUE : strpos($printer, "_laptop") !== FALSE;
		if ($isSecure)
		{
			echo "[SKIPPING] - " . $printer . "\n";
			continue;
		}

		$details = shell_exec("iprntcmd -i " . escapeshellarg($printer));
		$driver = "";
		$location = "";
		foreach(explode("\n", $details) as $infoLine)
		{
			$parts = explode(":", $infoLine);
			$key = trim($parts[0]);
			$val = trim($parts[1]);
			if (strpos($key, "Driver") !== FALSE)
				$driver = $val;
			else if ($key == "Location")
				$location = $val;
		}

		if ($driver == "")
			echo "[ERROR] - No PPD found for " . $printer . "\n";
		else
		{
			passthru("/usr/bin/python "
				. escapeshellarg($packager)
				. " " . escapeshellarg($printer)
				. " " . escapeshellarg($location)
				. " " . escapeshellarg($version)
			);
			echo "   (printer " . ($i + 1) . " of " . $totalPrinters . ")\n";
		}
	}
}

# the checkServer command accepts the iPrint server address.
# If you have multiple iPrint servers, call it multiple times
# in your script, like this:
checkServer("printers.denison.edu");
checkServer("labprinters.denison.edu");
